Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do basename on second field in a file and replace it in line

Tags:

bash

sed

awk

I'm trying to get something like basename of second field in a file and replace it:

$ myfile=/var/lib/jenkins/myjob/myfile

$ sha512sum "$myfile" | tee myfile-checksum
$ cat myfile-checksum
deb32b1c7122fc750a6742765e0e54a821 /var/lib/jenkins/myjob/myfile

Desired output:

deb32b1c7122fc750a6742765e0e54a821 myfile

So people can easily do sha512sum -c myfile-checksum with no manual edits.

With sed or awk, that is how far i made it for now :)

awk -F/ '{print $NF}' myfile-checksum
sed -i "s|${value}|$(basename $value)|" myfile-checksum

Thanks.

like image 217
Filip Stefanov Avatar asked Nov 24 '25 18:11

Filip Stefanov


1 Answers

You can set the field separators to both spaces and slashes and print the first and last fields:

awk -F" |/" '{print $1, $NF}'

With your input:

$ awk -F" |/" '{print $1, $NF}' <<< "deb32b1c7122fc750a6742765e0e54a821 /var/lib/jenkins/myjob/myfile"
deb32b1c7122fc750a6742765e0e54a821 myfile

In case your filename contain spaces, do remove everything from the first field up to the last slash, as indicated by Ed Morton:

$ awk '{hash=$1; gsub(/^.*\//,""); print hash, $0}' <<< "deb32b1c7122fc750a6742765e0e54a821 /var/lib/jenkins/myjob/myfile with spaces"
deb32b1c7122fc750a6742765e0e54a821 myfile with spaces
like image 189
fedorqui 'SO stop harming' Avatar answered Nov 27 '25 15:11

fedorqui 'SO stop harming'



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!