LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Tips on using bash script to edit a windows text file (https://www.linuxquestions.org/questions/linux-newbie-8/tips-on-using-bash-script-to-edit-a-windows-text-file-4175532975/)

weezy99 02-03-2015 04:00 PM

Tips on using bash script to edit a windows text file
 
I have a bash script executing on an AIX server to a windows share directory to update a windows text file. Most of the file is edited as expected but I have 3 issues that I am not sure how to resolve.

1. Windows text file contains a double backslash (\\) and the \\ is being written back as a single \ which corrupts the file.
2. I am not getting the last line of text in the file written back out.
3. Some lines of text are not written back out completely.

Here is a snippet of my bash script:
cp $Directory/Somefile $Directory/Somefile.$(date +'%Y%m%d')
cat /dev/null > ${HOME}/temp.out

while read -r inpLine; do
patternFound=n
echo ${inpLine} | grep -q 'SOMEPATTERN='
if [ $? = 0 ]; then
patternFound=y
echo "##${inpLine}" >> ${HOME}/temp.out
echo "SOMEPATTERN=newValue" >> ${HOME}/temp.out
fi

if [ ${patternFound} = "n" ]; then
echo ${inpLine} >> ${HOME}/temp.out
fi

done < $Directory/Somefile
mv ${HOME}/temp.out $Directory/Somefile

unSpawn 02-03-2015 04:51 PM

Quote:

Originally Posted by weezy99 (Post 5311494)
1. Windows text file contains a double backslash (\\) and the \\ is being written back as a single \ which corrupts the file.

In UNIX the backslash is one of the escape chars so if you need one as literal backslash you have to escape it:
Code:

~]$ echo "\\\\"
\\
 ~]$ echo "\\\\\\"
\\\


Quote:

Originally Posted by weezy99 (Post 5311494)
2. I am not getting the last line of text in the file written back out.

Might be a line ending issue?


Quote:

Originally Posted by weezy99 (Post 5311494)
3. Some lines of text are not written back out completely.

Running your script with the appropriate verbose, trace and or debug switches for your shell will help you understand how lines are executed.

jlinkels 02-03-2015 05:46 PM

Maybe a stupid idea, but running dos2unix on the file before editing the file and unix2dos afterwards might solve some compatibility problems.

Awk is better suited for this task, but if this project is only one of a kind it might not be worth the effort to learn it.

And please post code snippets in [.CODE][./CODE] tags.

jlinkels

weezy99 02-11-2015 08:09 AM

Sorry I am new to forum and didn't read the rules about how to appropriately post code snippets. Also very new to AIX/Linux and bash.
The resolution to my issue was to change from echo approach to sed and handle the special characters.


All times are GMT -5. The time now is 12:13 PM.