简体   繁体   English

使用sed / awk编辑文件

[英]Edit a file using sed/awk

I have a file which contains the following data: 我有一个包含以下数据的文件:

wednesday
Weekday

thursday
Weekday

friday
Weekday

saturday
MaybeNot

sunday
MaybeNot

monday
Weekday

tuesday
Weekday

I would like to insert a string $:$ in front of each alternate line such that the file is rewritten as follows: 我想在每条替换行的前面插入一个字符串$:$ ,以便将文件重写如下:

wednesday
$:$Weekday

thursday
$:$Weekday

friday
$:$Weekday

saturday
$:$MaybeNot

sunday
$:$MaybeNot

monday
$:$Weekday

tuesday
$:$Weekday

How would I achieve this using awk/sed? 我将如何使用awk / sed实现此目的?

ok. 好。 here. 这里。

cat << EOF | awk -vRS="" '{print $1 "\n$:$" $2 "\n" }'       
wednesday
Weekday

thursday
Weekday

friday
Weekday

saturday
MaybeNot

sunday
MaybeNot

monday
Weekday

tuesday
Weekday
EOF

gives... 给...

wednesday
$:$Weekday

thursday
$:$Weekday

friday
$:$Weekday

saturday
$:$MaybeNot

sunday
$:$MaybeNot

monday
$:$Weekday

tuesday
$:$Weekday

If your file doesn't start with a newline and has newlines as shown in your question then use: 如果您的文件不是以换行符开头,而是包含问题所显示的换行符,请使用:

sed -i.bak '2s/^/$.$/;3,${n;n;s/^/$.$/;}' file

If file has no new lines and you want to put $.$ before every alternate line as you state in question: 如果file没有新行,并且您要在有问题的状态下$.$放在每行后面:

sed -i.bak 'n;s/^/$.$/' file

To prepend $:$ to every 3rd line starting with line 2 do this with GNU sed: 要在第2行开始的每第3行前加上$:$ ,请使用GNU sed:

sed -i '2~3s/^/$:$/' infile

Note that this will overwrite infile so be careful. 请注意,这将覆盖infile因此请小心。

Using awk - the variable n is initialised in the BEGIN pattern, then the lines are printed as required by testing the odd/eveness of n . 使用awk-将变量n初始化为BEGIN模式,然后根据需要通过测试n的奇/均匀性来打印行。

awk 'BEGIN{n=1}
{
     if (n++ % 2)
       print $0
     else
       print "$:$"$0
}' datafile

ssed use perlre, so if you know perlre, it simple. ssed使用perlre,因此,如果您知道perlre,就很简单。 use -i if you want modify target file. 如果要修改目标文件,请使用-i。

cat t|ssed 's/^\([A-Z]\)/$:$&/'

wednesday

$:$Weekday

thursday

$:$Weekday


friday

$:$Weekday

saturday

$:$MaybeNot

sunday

$:$MaybeNot

monday

$:$Weekday

tuesday
$:$Weekday
awk '/^[[:upper:]]/ {$0="$:$"$0}1' file

to replace in the file 在文件中替换

awk '/^[[:upper:]]/ {$0="$:$"$0}1' file > tmp ; mv tmp file

EDIT Another version (this needs the formatting to be the same all time): 编辑另一个版本(这需要格式始终保持一致):

awk 'NR%3==2 {$0="$:$"$0} 1' file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM