I want to execute a bash script on a list of text files (using a for
loop, I guess), redirecting stdout to a file with the same path as the text file from stdin plus an extension (for example .txt or .sam, or just add a ~ to the end of the stdin path to make it different).
Asked
Active
Viewed 3,171 times
0

Alex Grin
- 8,121
- 6
- 33
- 57

WarioBrega
- 195
- 1
- 3
- 10
-
I got lost, could you put an example of what you want to accomplish? – Freddy Apr 11 '12 at 16:46
-
2@tripleee you did observe that this question was asked in 2012, and the one you claim it duplicates was asked in 2013, right? I mean, you *did* think to check the dates so that you don't cause an anachronism and destroy the space0time continuum. – Charlie Martin Jun 30 '15 at 06:25
-
18@CharlieMartin Thanks for asking. I didn't notice, no; but the age of a question is a secondary concern. A question with a better exposition of the problem and/or multiple good answers is a better choice as the "duplicate of" target, regardless of the age of the questions; and when both questions are old, in particular, it is not unusual for the newer of the two to be more canonical. – tripleee Jun 30 '15 at 06:44
1 Answers
4
Okay, assuming the list isn't too long, you can start with
for i in `cat list`
do
# do stuff here
done
If the list is long enough to risk a too-long command line, there's a while variant
cat list | while read i
do
# do stuff here
done
you can construct the file name using basename(1) to get rid of the old extension suffix; for say .txt to .bak use
`basename .txt ${i}`.bak
you can get the path part using dirname(1)
Since macros are expanded early, you can simply construct the command line in variables and expand them. Where op and np are your path names
command < $op > $np
There's a lovely on-line book, the bash Advanced Scripting Guide that covers this and more.

Charlie Martin
- 110,348
- 25
- 193
- 263
-
http://mywiki.wooledge.org/DontReadLinesWithFor and obviously, the `cat` is [useless](http://www.iki.fi/era/unix/award.html). – tripleee Jun 30 '15 at 04:26
-
See also http://wiki.bash-hackers.org/scripting/tutoriallist#rv_abs for some (very mild) caveats regarding the ABS guide. The consensus is that it should not be your first-stop shop for scripting advice. The linked page recommends some other tutorials (scroll back up a couple of notches). – tripleee Jun 30 '15 at 04:27
-
3Maybe follow up on meta: http://meta.stackoverflow.com/questions/298192/disagreement-on-duplication-action – tripleee Jun 30 '15 at 06:42