Saturday, September 30, 2023
1
rated 0 times [  1] [ 0]  / answers: 1 / hits: 530  / 5 Months ago, wed, may 10, 2023, 7:13:08

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: FolderSome FolderA file name.txt.


I've tried this, with and without double quotes:


sed -i 's/
" Type: "/^"Type: "/g' file.txt

That gives me no errors, but also no changes. Also tried this:


awk '/ "        Item: " / { printf "%s", $0"^" } / "        Type: " / { gsub(/^[ 	]+/,"",$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.


More From » command-line

 Answers
0

I would use awk … It is a straightforward one-liner like so:


awk '/Item:/ { printf "%s", $0"^" } /Type:/ { gsub(/^[ 	]+/,"",$0); print $0 }' file

That is … If the line has Item: in it, then print it without appending a newline(printf doesn't append a newline by default) but append the ^ character at the end … and if the line has Type: in it, then remove all leading space and print it appending a newline(print appends a newline by default).


The above command will not modify the original file but, will rather output modified text in the terminal.


To edit the original file in-place, use the -i inplace option of GNU awk(Might be the default on Ubuntu ... Check with awk -W version) or if not, you can install gawk then use it like so:


gawk -i inplace '/Item:/ { printf "%s", $0"^" } /Type:/ { gsub(/^[ 	]+/,"",$0); print $0 }' file

[#73] Thursday, May 11, 2023, 5 Months  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
biryanrownies

Total Points: 396
Total Questions: 90
Total Answers: 106

Location: Saint Lucia
Member since Sun, Sep 5, 2021
2 Years ago
biryanrownies questions
Wed, Sep 7, 22, 18:13, 1 Year ago
Fri, Dec 3, 21, 02:50, 2 Years ago
Sat, Feb 12, 22, 16:02, 2 Years ago
Sat, Apr 15, 23, 09:22, 6 Months ago
;