0

I have a file with list of directories:

$ cat dirs.txt
/some/path
/other/path
/some/another/one

Current directory is /home/loom

$ echo $PWD
/home/loom

I would like to add $PWD to each row of dirs.txt like the following:

/home/loom/some/path
/home/loom/other/path
/home/loom/some/another/one

I unsuccessfully tried the command:

$ cat dirs.txt | awk '{print $PWD$1}'
/some/path/some/path
/other/path/other/path
/some/another/one/some/another/one

It just doubled each row. What command solves my problem?


I mean parametric answer, not cat dirs.txt | awk '{print "/home/loom" $1}'

jesse_b
  • 37,005
Loom
  • 3,953

2 Answers2

3

PWD is a shell variable and therefore won't expand inside the single quotes used by awk.

awk -v pwd="$PWD" '{print pwd$1}' dirs.txt

This will set the pwd awk variable to the value of the PWD shell variable and then print column 1 of each line in dirs.txt with that value prepended to the beginning.

Using GNU awk you can use the -i inplace option to overwrite your file with the output, otherwise you will have to redirect it to a new file and overwrite the old file with that if desired.

jesse_b
  • 37,005
  • +1. BTW, if the variable has been exported, you can use the awk built-in array ENVIRON. e.g. awk '{print ENVIRON["PWD"]$1}' dirs.txt. Using -v makes for more readable code, IMO. Also watch out for filenames containing the = character: awk will interpret them as variable assignments similar to -v (but this happens after any BEGIN block). e.g. echo | awk '{print foo}' foo=bar – cas Aug 16 '19 at 02:15
  • The functional difference between using -v and ENVIRON is that the former will expand escape sequences (so foo\tbar will become foo<tab>bar) while the latter won't. You can use ENVIRON for non-exported variables too, you just need to set the shell variable to itself on the awk command line, e.g. shellvar="$shellvar" awk 'BEGIN { awkvar=ENVIRON["shellvar"].... The issue about = (or -) in file names only applies to arguments, not to input. – Ed Morton Aug 16 '19 at 13:01
1

There're of course more ways to do so, so since you're asking for any command that solves your problem, another way could be this:

while read -r line; do echo "${PWD}${line}"; done < "dirs"
pavelsaman
  • 226
  • 1
  • 7