Home > OS >  Getting the absolute path of file in awk
Getting the absolute path of file in awk

Time:05-26

Is there a way to get the absolute path from a filename in awk, like what we can get from realpath ...? The case is that i want to convert a file with a list of relative paths, which i wanna convert to a absolute one. like this:

audio1_16000 feats.ark:21
audio2_16000 feats.ark:415577
audio3_16000 feats.ark:869055
audio4_16000 feats.ark:1292932
audio5_16000 feats.ark:1715691

what i want is:

audio1_16000 /home/simon/my-audios/feats/feats.ark:21
audio2_16000 /home/simon/my-audios/feats/feats.ark:415577
audio3_16000 /home/simon/my-audios/feats/feats.ark:869055
audio4_16000 /home/simon/my-audios/feats/feats.ark:1292932
audio5_16000 /home/simon/my-audios/feats/feats.ark:1715691

Or, is there any alternative bash commands which i could utilize for this scenario?

CodePudding user response:

Use readlink -f

readlink -f feats.ark

should be /home/simon/my-audios/feats/feats.ark

CodePudding user response:

awk '
$2 !~ /^\// {sub(/^\.//, "", $2; $2 = ENVIRON["PWD"]"/"$2} 1' my-file

You can use the PWD environment variable. This script skips full paths and removes ./ if necessary. It won't work if the relative paths contain spaces, but could be modified to do so.

CodePudding user response:

You can run realpath -f within awk and take the output like:

awk '{ split($2,a,":"); cmd=sprintf("readlink -f %s", a[1]); cmd | getline abspath; printf("%s %s:%s\n", $1, abspath, a[2]);}'

CodePudding user response:

Using awk

$ awk -v pwd="$(pwd)" '{$2=pwd"/"$2}1' feats.scp

CodePudding user response:

Found a solution not using awk, but sed:

# say 'feats.scp' is the file to convert
sed -r -i 's#feats.ark#'$(pwd)'/feats.ark#g' feats.scp

But I am still looking forward to awk solution.

CodePudding user response:

awk -F'[ :]' '{print $1" "$NF":"$3}' <( \
  paste -d" " \
       input.txt \
       <(awk -F'[ :]' '{print |"readlink -f "$2}' input.txt) \
)
  • Related