John Smith
John Smith

Reputation: 897

How do I replace the second occurrence of a whitespace in each line with 'sed' or 'awk'?

I have a file hashes which has many lines that look like this:

wget https://ipfs.io/ipfs/QmbKi6XiMmf4YfvKXhqVPymD1HDwJ3WqukjyLuEvnrZrCz The_Supremes_-_My_World_Is_Empty_Without_You_(lyrics).mkv

All the lines in hashes will follow the pattern:

wget https://ipfs.io/ipfs/hashthatis46characterlong nameOfAfileWithoutSpaces

as they are written by my script with the following lines of code:

find ~/pCloudDrive/VisualArts/Films/Fiction_Movies -maxdepth 1 -type f -size +200M -exec ipfs add --nocopy {} \;>>~/CS/ipfs/hashes && \
sed -i 's;added ;wget https://ipfs.io/ipfs/;g' ~/CS/ipfs/hashes

All hashes are going to be 46-character long and they typically start with 'Qm' but this may not necessarily be the case in the future.

I want to replace the second space of each line of this file with ' -O ' so that it looks like:

wget https://ipfs.io/ipfs/hashthatis46characterlong -O nameOfAfileWithoutSpaces

I tried sed 's/[0-9A-z]{46,46}\s/& -O /g' hashes but to no avail - I get the following output:

sed: -e expression #1, char 27: Invalid range end

How do I do this? Would awk present a better solution for this problem than sed?

Upvotes: 2

Views: 908

Answers (4)

Daweo
Daweo

Reputation: 36560

As you have nameOfAfileWithoutSpaces it is possible to get desired result another way using GNU sed, namely:

s/\([^[:space:]]*\)$/-O \1/

this does capture non-whitespace characters which are followed by end of line ($) then does replace by -O followed by these characters. I tested in using sed.js.org and for input

wget https://ipfs.io/ipfs/hashthatis46characterlong nameOfAfileWithoutSpaces
wget https://ipfs.io/ipfs/hashthatis46characterlong anotherName

output is

wget https://ipfs.io/ipfs/hashthatis46characterlong -O nameOfAfileWithoutSpaces
wget https://ipfs.io/ipfs/hashthatis46characterlong -O anotherName

Upvotes: 2

kvantour
kvantour

Reputation: 26481

Another awk:

$ awk '{$3="-O" OFS $3}1' file

Upvotes: 1

James Brown
James Brown

Reputation: 37414

Using GNU awk and gensub() to change the second occurrence on each record:

$ awk '{print gensub(/ /," -O ","2")}' file

For example:

$ echo 1 2 3 4 5  | awk '{print gensub(/ /," -O ","2")}'
1 2 -O 3 4 5

Upvotes: 3

Enlico
Enlico

Reputation: 28416

As simple as this

sed 's/ / -O /2' input

where the trailing 2 in the sed command means "the second occurrence".

Upvotes: 3

Related Questions