Hi,
I want to remove the spaces from all the lines matching a particular pattern from my file. For instance in file abc.txt I have following data.
Header,This is the header
111,this is 1st record
222, this is 2nd record
333, this is 3rd record
Footer,3 records found
Footer,111222333
In this data, the 1st Footer has spaces between "3", "records" and "found" and the 2nd footer has trailing spaces after "111222333". I want to remove the spaces only from the records which starts with keyword "Footer".
Expected Output 1:
Header,This is the header
111,this is 1st record
222, this is 2nd record
333, this is 3rd record
Footer,3recordsfound
Footer,111222333
Also, is there a way I can just remove the trailing spaces from matched rows?
Expected Output 2:
Header,This is the header
111,this is 1st record
222, this is 2nd record
333, this is 3rd record
Footer,3 records found
Footer,111222333
Try something like:
sed '/Footer/s/ //g' file
I don't get the the 2nd output, which is identical to the input..
Thanks!
2nd output actually looks identical but the input has trailing spaces in the last record whereas the output doesn't have any trailing spaces. Thats the difference.
OK, the sed command should get rid of those as well...
--
If there can also be TABs you could try:
sed '/Footer/s/[[:blank:]]//g' file
or
awk '/Footer/{$1=$1}1' OFS= file
Thank you Scrutinizer ... took a lead from your example and came up with below.
To remove all spaces from the row that begins with keyword "Footer"
sed '/^Footer/s/ //g' file1 > file2
To remove only the trailing spaces from the row that begins with keyword "Footer"
sed '/^Footer/s/ *$//g' file1 > file2
Note that when you're dealing with an anchored expression (i.e., ^expression
or expression$
), the g
flag is superfluous. The command:
sed '/^Footer/s/ *$//' file1 > file2
produces exactly the same results as the command above.