Preamble:
So I have a project whereby I need to run a conversion tool on a bunch of files. There are multiple steps to the conversion, and it can take a while. Since these files aren’t necessarily in the same directory, I created a text file with the filenames to convert:
<filenames.txt>
/home/me/Documents/file1.txt
/home/me/Documents/file2.txt
/home/me/Documents/file3.txt
Problem:
I then have a bash script to run over these files, and do the conversion steps. However, I try and echo the phase and filename, and echo, in this case, sticks the echo’d text in the middle of the filename:
<script.sh>
cat filenames.txt | while read some_file
do
echo
echo "Begin FORMAT_A to FORMAT_B conversion..."
echo "FORMAT_A Filename:"
echo $some_file
formatb_dir= dirname $some_file | tr '\n' "/"
formatb_file= basename $some_file ".xml" | tr '\n' "_"
formatb=$formatb_dir$formatb_file"form_b.xml\n"
echo "FORMAT_B Filename:"
echo $formatb
done
Produces output like this:
Begin FORMAT_A to FORMAT_B conversion...
FORMAT_A Filename:
/home/me/Documents/file1.txt
/home/me/Documents/file1.txt_FORMAT_B Filename:
form_b.xml
Begin FORMAT_A to FORMAT_B conversion...
FORMAT_A Filename:
/home/me/Documents/file2.txt
/home/me/Documents/file2.txt_FORMAT_B Filename:
form_b.xml
Begin FORMAT_A to FORMAT_B conversion...
FORMAT_A Filename:
/home/me/Documents/file3.txt
/home/me/Documents/file3.txt_FORMAT_B Filename:
form_b.xml
“FORMAT_B Filename”, the echo’d text, has appeared before the appended text “form_b.xml”.
I looked at the man pages for dirname, basename, echo and tr, but I didn’t spot anything that looks like it’d cause what I’m seeing. I tried looking around on Google, but I’m not sure I’m asking the right questions (“bash echo text before variable”?).
Question: Why is my echo putting the echo’d text in the middle of my variable?
(possible related question: “Am I going about what I’m doing in completely the wrong way?”)
Edit: I accepted fortea’s answer because it walked me through what I didn’t understand about variables and getting the output from commands. That said, dogbane and Jonathan Leffler showed better ways of doing what I was doing.
The problem is in the declaration of variables:
Try a new line:
echo $formatb_dir: it does not contain anything because after the ‘=’ there is a blank space. Then bash readsdirname $somefile |tr '\n' "/"and it executes this command. The same when you create formatb_file, but this time the command is basename. (this is what appears before “FORMAT_B Filename:”).Then formatb is created correctly, but $formatb_dir and $formatb_file are empty, so $formatb will contain only
"form_b.xml\n".Then you echo “FORMAT_B Filename:”.
Then you echo $formatb, which will output “form_b.xml”.
So, you should use something like this:
Read here