如何替换最后一个字符并将字符插入字符串的开头?

时间:2017-08-14 16:16:40

标签: bash shell sed

说我有一个文本文件如下:

accio.
aguamenti.
alohomora.
aparecium.

我想得到的是:

-accio!
-aguamenti!
-alohomora!
-aparecium!

这是我尝试过的:

sed 's/.*[a-z]/-&!/g'

哪个收益率:

-accio!.
-alohomora!.

这是非常接近但显然不是我需要的。帮助

3 个答案:

答案 0 :(得分:1)

分两步:

$ sed 's/^/-/;s/.$/!/' infile
-accio!
-aguamenti!
-alohomora!
-aparecium!

第一个命令"替换"每行-的开头,有效插入;第二个命令用!替换最后一个字符。

答案 1 :(得分:1)

您需要使用捕获组来排除最后的角色:

$ sed  's/^\(.*\)\.$/-\1!/' file

或者分两步完成:

$ sed  -e 's/\.$/!/' -e 's/.*/-&/' file

答案 2 :(得分:0)

您可以使用捕获组:

<?php

header('Content-Type: application/json');

/*
* DataTables example server-side processing script.
*
* Please note that this script is intentionally extremely simply to show how
* server-side processing can be implemented, and probably shouldn't be used as
* the basis for a large complex system. It is suitable for simple use cases as
* for learning.
*
* See http://datatables.net/usage/server-side for full details on the server-
* side processing requirements of DataTables.
*
* @license MIT - http://datatables.net/license_mit
*/

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Easy set variables
*/

// DB table to use
$table = 'pedidos';

// Table's primary key
$primaryKey = 'id';

// Array of database columns which should be read and sent back to DataTables.
// The db parameter represents the column name in the database, while the dt
// parameter represents the DataTables column identifier. In this case simple
// indexes

$columns = array(
array( 'db' => 'id', 'dt' => 0 ),
array(
'db' => 'pedidos_data',
'dt' => 1,
'formatter' => function( $d, $row ) {
return date( 'jS M y', strtotime($d));
}
),
array( 'db' => 'pedidos_nome', 'dt' => 2 ),
array( 'db' => 'pedidos_cpf', 'dt' => 3 ),
array( 'db' => 'pedidos_rg', 'dt' => 4 ),
array( 'db' => 'pedidos_nascimento', 'dt' => 5 ),
array( 'db' => 'pedidos_status', 'dt' => 6 ),

);

// SQL server connection information
$sql_details = array(
'user' => 'root',
'pass' => '',
'db' => 'prevmaisaude',
'host' => 'localhost'
);

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* If you just want to use the basic configuration for DataTables with PHP
* server-side, there is no need to edit below this line.
*/

require( 'ssp.class.php' );

echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);

如果你的专栏在问题的最后一个字母之前只包含小写英文字母,那么你也可以使用:

sed -E 's/^(.*).$/-\1!/' file

-accio!
-aguamenti!
-alohomora!
-aparecium!