linux - Find, Replace or Insert - command Line -
i have list similar :
what want do? import text file opening in excel import text file connecting export data text file saving change delimiter used in text file change separator in .csv text files
using sed can find match on 'connecting' , replace line:
sed 's^.*connecting.*^import text file opening it^g' crontab
this should change above list :
what want do? import text file opening in excel import text file opening export data text file saving change delimiter used in text file change separator in .csv text files
however need able is:
if line exists containing word connecting
, replace line, if line doesn't exist add end of list new line.
i know can echo "import text file opening it" >> list
add line end of list, there anyway can within 1 command ? or commands can run in 1 instance ?
thanks
an easy way use awk
:
awk 'begin { s = "import text file opening it" } /connecting/ { $0 = s; n = 1 } 1; end { if(!n) print s }' filename
that works follows:
begin { # before else: s = "import text file opening it" # remember string shorter # name don't have repeat } /connecting/ { # if line contains "connecting", $0 = s # replace line string n = 1 # , raise flag we've done so. } 1 # print end { # in end: if(!n) { # if string wasn't yet printed, print s # now. } }
alternatively, can use sed
's hold buffer. example:
sed '1 { x; s/.*/import text file opening it/; x; }; /connecting/ { s/.*//; x; }; $ { g; s/\n$//; }' filename
this works follows:
1 { # while processing first line x # swap hold buffer, pattern space s/.*/import text file opening it/ # write text pattern space x # swap back. } # hold buffer contains # line want insert, , # pattern space first line. /connecting/ { # lines: if line contains # "connecting" s/.*// # empty pattern space x # swap in hold buffer. # if happened, hold buffer # empty , pattern space # contain "import ..." } $ { # last line: g # append hold buffer pattern space. # if hold buffer empty (i.e., # used somewhere else), # appends newline, s/\n$// # remove if happened. }
note sed
code depends on fact there's 1 line contains "connecting." if there more such lines, replaced empty lines because hold buffer empty when second line comes around. possible handle case, you'd have decide should happen in it. since replied in comments there's 1 such line, didn't feel need guess.
Comments
Post a Comment