xsus
xsus

Reputation: 25

Bash Script : Edit .txt by Line

I have a text file with unknown length. There are two values on each line:

VALUE1[SPACE]VALUE2

Now I have to get another (or the same) file with a new List like:

0.0.0.0/rep/com/bla/blub/VALUE1/VALUE2/VALUE1-VALUE2.zip

...for each line I have in the list with the two values. How can I do this?

Upvotes: 0

Views: 141

Answers (4)

Mark Reed
Mark Reed

Reputation: 95385

I would use sed for this:

sed $'s,^[ \t]*\([^ \t]*\)[ \t][ \t]*\([^ \t]*\).*$,0.0.0.0/rep/com/bla/blub/\1/\2/\1-\2.zip,' filename >new-filename

You could modify the original file in place if you prefer by adding -i.bak: sed -i.bak $'s,...,'.

Upvotes: 0

swalog
swalog

Reputation: 4546

The format of your input data file is (VALUE1 VALUE2).. You first remove the initial (, and latter ). There are many ways to do this, here is one

sed 's/(//g' yourfile | sed 's/).//g' 

You can then pass this over to awk. Here $1 corresponds to the first column, and $2 to the second:

sed 's/(//g' yourfile | sed 's/).//g' | awk '{print "0.0.0.0/rep/com/bla/blub/"$1"/"$2"/"$1"-"$2".zip"}'

Upvotes: 0

Stefano Sanfilippo
Stefano Sanfilippo

Reputation: 33116

I assume that VALUE1 and VALUE2 contain no spaces, otherwise the first definition becomes ambigous. With this hypothesis, you can split a line at the first space using cut and compose the filename variable using string interpolation:

cat txt-File | while read VALUE1 VALUE2 _; do
    filename="0.0.0.0/rep/com/bla/blub/$VALUE1/$VALUE2/$VALUE1-$VALUE2.zip"

    # Do something with filename...
    stat "$filename"
done

Upvotes: 0

JNevill
JNevill

Reputation: 50308

This is a good usecase for awk (Updated to take care of the parantheses):

awk -F" " '{ gsub("\\(", "", $1); gsub("\\)", "", $2);print "0.0.0.0/rep/com/bla/blub/"$1"/"$2"/"$1"-"$2".zip"}' test.txt > yournewfile.txt

This will split each line with a space, replace the opening parentheses in your first token $1 and replace the closing parentheses in your second toke $2 and then use values in their respective tokens $1 and $2 in the string you are outputing with print

Upvotes: 1

Related Questions