Warm tip: This article is reproduced from stackoverflow.com, please click
bash sed grep

Delete words in a line using grep or sed

发布于 2020-03-27 10:31:47

I want to delete three words with a special character on a line such as

Input:

\cf4 \cb6 1749,1789 \cb3 \

Output:

1749,1789

I have tried a couple sed and grep statements but so far none have worked, mainly due to the character \.

My unsuccessful attempt:

sed -i 's/ [.\c ] //g' inputfile.ext >output file.ext
Questioner
Alan De Moin
Viewed
122
vintnes 2019-07-03 00:51

Awk accepts a regex Field Separator (in this case, comma or space):

$ awk -F'[ ,]' '$0 = $3 "." $4' <<< '\cf4 \cb6 1749,1789 \cb3 \'
1749.1789
  • -F'[ ,]' - Use a single character from the set space/comma as Field Separator
  • $0 = $3 "." $4 - If we can set the entire line $0 to Field 3 $4 followed by a literal period "." followed by Field 4 $4, do the default behavior (print entire line)

Replace <<< 'input' with file if every line of that file has the same delimeters (spaces/comma) and number of fields. If your input file is more complex than the sample you shared, please edit your question to show actual input.