I am trying to create a file occurent within my /tmp directory of each file containing a speicific string.

The problem is that the call to basename {} does not seem to work. Neither this, neither echo basename {}.

grep -R 'mystring' . | cut -d: -f 1 | uniq | xargs -n 1 -I {} touch /tmp/`basename {}`

Does anybody know how could I get the basename function executed on the xargs parameter ?

  • 1
    What are you really trying to do? Has it occurred to you that there may be multiple matching files in different places with the same basename? – jw013 Jul 15 '12 at 19:16
  • @jw013 I am well aware of this fact. But in this exact case this is not a problem. – Spredzy Jul 21 '12 at 17:37

try this:

grep -R 'mystring' . | cut -d: -f 1 | uniq| xargs -n 1 -I {} -t -i ksh  -c "touch /tmp/$(basename {})"
  • 1
    Using sh instead of ksh works as well. – daniel kullmann Jul 17 '12 at 12:01
  • Wouldn't you need single quotes there? – Tilo Wiklund Jul 17 '12 at 14:57
  • both single and double quto will work for this, its better use single quotes. – sfgroups Jul 18 '12 at 0:40

The problem is that the backticks are expanded too early (i.e. not once for each argument sent to xargs). There might be a better way, but you should be able to get away with an explicit bash loop:

grep -R 'mystring' . | cut -d: -f 1 | uniq | while read f; do touch "/tmp/`basename $f`"; done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.