Bash – Fix for Loop Wget Directory Creation Error

bashwget

As a Ubuntu beginner. I am trying to download links from multiple text files with wget2 in batch. The -P "$f" creates directory name with .txt suffix. Is it possible to ignore .txt for -P "$f". Any modification suggestions.

for f in *.txt;do wget2 -i "$f" -P "$f";done

Best Answer

${f%.txt} expands like $f but with .txt suffix (if any) removed. Don't forget to double-quote it like you correctly quoted $f.

for f in *.txt; do wget2 -i "$f" -P "${f%.txt}"; done

The syntax is portable, it takes a pattern (like filename generation a.k.a. globbing pattern, not a regex). E.g. ${f%.*} gives you everything but the extension, no matter what the extension is. Here the dot is literal and the asterisk is a wildcard.

POSIX specifies few features like this. Bash supports them and more. Documentation:

Related Question