简体   繁体   中英

How to modify the file content using sed

IP file - 1.txt

$ cat 1.txt
'&1'
'&2'
'&3'

if I want the o/p as

:1
:2
:3

using sed, (or any command for that matter), how do I achieve?

awk '{gsub(/'"^'"'|'"'$"'/,"");gsub(/&/,":")}1' input
:1
:2
:3

Here , awk 's gsub function is used to replace single quotes to blank and another gsub is used to replace & to : . 1 means,print in awk.

You can get your o/p by using below 2 commands.

--> sed -e '/1/b' -e '/2/b' -e '/3/b' -ed 1.txt or --> gsed '/1:2:3/!d' 1.txt

Is this fine ?

sed -e 's/.*[^0-9]\([0-9]\+\)[^0-9]*$/:\1/' 1.txt

:1
:2
:3
$ cat 1.txt 
Monday {'&1', 'Morning', 'Breakfast'}
Tuesday {'&2', 'Noon', 'Lunch'}
Wednesday {'&3', 'Evening', 'Supper'}
Thursday {'&4', 'Night', 'Dinner'}

$ sed -E 's/\x27&([0-9]+)\x27/:\1/' 1.txt 
Monday {:1, 'Morning', 'Breakfast'}
Tuesday {:2, 'Noon', 'Lunch'}
Wednesday {:3, 'Evening', 'Supper'}
Thursday {:4, 'Night', 'Dinner'}
  • \\x27& match single quote and & (See ASCII set for reference)
  • ([0-9]+) capture digits for back-referencing
  • \\x27 match single quote
  • :\\1 replace matched pattern with : and captured digits
  • Note: some sed versions use -r instead of -E for extended regex option

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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