An answer to another question suggests sed -i 's/original/replacement/g' file.txt
to replace specific words in a text file. My starting situation looks like this:
Item: PRF
Type: File
Item: AOX
Type: Folder
Item: DD4
Type: File
My ending situation should look like this:
Item: PRF^Type: File
Item: AOX^Type: Folder
Item: DD4^Type: File
Notes: (1) The Ask Ubuntu interface seems to suppress some of the leading spaces before Item: and Type:. There are in fact eight leading spaces. (2) I may have erred in using simplistic examples of Item. The items are actually partial Windows paths (lacking e.g., D:), some of which are quite long. A more accurate example would be Item: Folder\Some Folder\A file name.txt.
I've tried this, with and without double quotes:
sed -i 's/\n" Type: "/\^"Type: "/g' file.txt
That gives me no errors, but also no changes. Also tried this:
awk '/ " Item: " / { printf "%s", $0"^" } / " Type: " / { gsub(/^[ \t]+/,"",$0); print $0 }' source.txt
I tried that to verify that I would be changing only those entries with eight blank spaces before "Item." That didn't work. Trying it with no spaces and no double quotes, as in the answer (below), also failed. Trying it with gawk -i inplace
produced source.txt containing zero bytes.
My title initially specified sed
. An answer proposing awk
alerted me to that alternative, which (now that I'm looking at it) seems more capable. But I cannot figure out how to make it work.
sed -i
, you'd need to use GNU awk with the-i inplace
option – muru Jan 16 '23 at 12:00sudo apt install gawk
the-i inplace
option did modify source.txt, though with undesirable results (see edited question, above). – Ray Woodcock Jan 16 '23 at 12:18/ " Item: " /
,/ " Type: " /
- these don't match anything in the input file you have shown, so nothing gets printed, so your input file is replaced with nothing. – muru Jan 16 '23 at 12:22\r\n
carriage return(Windows style newlines) and you need to run it through e.gdos2unix file
to correct that before processing it with eithersed
orawk
– Raffa Jan 16 '23 at 12:36gedit
and used Save As to change the line ending from Windows to Unix\Linux. – Ray Woodcock Jan 16 '23 at 21:41