Home > Net >  How to replace the links inside of a file by sed command
How to replace the links inside of a file by sed command

Time:11-01

I have a file named 1.txt and it contains below 3 URLs, each of them following a http link, which I want to change them using sed command. The link could be regard as a string without space.

  URL1: https://i.stack.imgur.com/Zw5ZK.png
  URL2: https://i.stack.imgur.com/cT8Pv.png
  URL3: https://i.stack.imgur.com/L3Syn.png

My purpose is to use something like below to replce those 3 links from command line, like:

sed **** 1.txt https://abc/1.png https://abc/2.png https://abc/3.png

After the command executes, the new content of 1.txt would be:

  URL1: https://abc/1.png
  URL2: https://abc/2.png
  URL3: https://abc/3.png

CodePudding user response:

Something like this?

$ awk '{a=gensub(/URL([^:] ):/,"\\1",1,$1);sub(/i\.stack\.imgur.com\/.*/,"abc",$2);print $1,$2"/"a".png"}' 1.txt
URL1: https://abc/1.png
URL2: https://abc/2.png
URL3: https://abc/3.png

a=gensub(/URL([^:] ):/,"\\1",1,$1) captures the numeric part of the URL in the first column. sub(/i\.stack\.imgur.com\/.*/,"abc",$2) replaces the entire actual url with https://abc in the second column.

print $1,$2"/"a".png" prints the new line with the new, numbered png.

CodePudding user response:

Using sed

$ sed -E 's~(URL([0-9]):[^:]*://).*~\1abc/\2.png~' input_file
URL1: https://abc/1.png
URL2: https://abc/2.png
URL3: https://abc/3.png

CodePudding user response:

It is much easier to do with awk:

awk 'BEGIN {FS=OFS="//"} {$2 = "abc/"   n ".png"} 1' file

  URL1: https://abc/1.png
  URL2: https://abc/2.png
  URL3: https://abc/3.png

Alternative awk solution using sub:

awk '{sub(/\/\/. /, "//abc/"   n ".png")} 1' file

  URL1: https://abc/1.png
  URL2: https://abc/2.png
  URL3: https://abc/3.png

CodePudding user response:

Here's a simple wrapper which changes your command line parameters into a proper sed script. We are simply indexing by line number.

#!/bin/bash

file=$1
shift

script=()  # empty array
for ((i=1; i<=$#; i  )); do
    script =(-e "${i}s|http.*|${!i}|")
done
sed "${script[@]}" "$file"
  • Related