0

Scenario: I have a file called text.txt that contains items in the following format:

    002 jack /data/jack_profile_0606112019.doc
    004 jack /data/jack_pic_06062019.jpg
    009 jane /data/jack_profile_06162019.doc
    012 tommy /data/jack_profile_06262019.doc
    002 jackf /data/jackf_profile_09062019.doc
    002 jack /data/jack_profile_0606112019.pdf

I am writing a Bash script to search for jack, retrieve the last group (ex /data/jack_profile_06062019.doc), and save that information to a variable.

`files="$(grep ' jack ' ../data/text.txt | cut -d ' ' -f3`)"
`echo $files`

returns /data/jack_profile_0606112019.doc /data/jack_pic_06062019.jpg /data/jack_profile_0606112019.pdf

This is great so far I proceeded to build the basic by iterating through lines in $files and printing out the outputs adding the path to the root directory ~.

`for item in $files; do echo ~$item; done`

Here is the output:

    /home/janedoe/data/jack_profile_0606112019.doc 
    /data/jack_pic_06062019.jpg 
    /data/jack_profile_0606112019.pdf

Here is what I expected:

    /home/janedoe/data/jack_profile_0606112019.doc 
    /home/janedoe/data/jack_pic_06062019.jpg 
    /home/janedoe/data/jack_profile_0606112019.pdf

Notice that only the first file returns the actually full path and not the rest. This is where I think I am stuck.

Finally, add the if condition to check if the files from the $file exist and output the info to a file

    for item in $files; do
      if [ -e ~$item ]; then echo ~$item >> output.txt; fi;
    done
`cat output.txt` 

should read /home/janedoe/data/jack_profile_0606112019.doc /home/jan/dedoeata/jack_pic_06062019.jpg

  • You really didn't want back quotes around the `files=...` and `echo $files` lines, did you? As you are using `$(...)` command substitution, did you know that putting backquotes around a command is the old-fashioned (but highly portable) version of the same **command substition** technique as your `$(...)`? Keep your code clean so readers aren't distracted by such questions as "do they really want old-fashioned cmd-substitution? And Why? ..." (-;! Good luck. – shellter Aug 30 '23 at 21:45
  • See [Why use $HOME over ~ (tilde) in a shell script?](https://stackoverflow.com/q/5930671/4154375). – pjh Aug 30 '23 at 21:53
  • If you need only the **last** _jack_, why are you putting all of them into `files`? – user1934428 Aug 31 '23 at 08:03

0 Answers0