Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Script needed to Strip <cr> from text files 2

Status
Not open for further replies.

JohnDin

MIS
Sep 11, 2000
2
0
0
GB

Hi all,

I'm new to Unix scripting and in particular file manipulation ! I need a script that will strip carriage return characters out of a text file. Quick and dirty with an explanation would be great thanks.
Any help much appreciated.

Regards,

John.

jdinwoodie@aol.com [sig][/sig]
 
Is this to strip carriage return characters from a DOS file? If so, create a new file containing the following shell script:
[tt]
#!/bin/sh

sed -e's/^M$//' $1 > /tmp/$1.new

# Copy original file to a backup.
cp $1 $1.orig

# Move the new copy over the top of the original file.
mv /tmp/$1.new $1

# Remove the temporary file.
rm /tmp/$1.new
[/tt]

The ^M is the control-M character, or carriage return. To enter this character if you are using vi, press Ctrl+V followed by Ctrl+M.

Run the script as &quot;myscript file.txt&quot;, where file.txt is the name of the file you want to strip <CR> out of. Everywhere you see &quot;$1&quot; in the script it is referring to the first argument. ie, the filename.

The sed line uses the &quot;swap&quot; operator &quot;s&quot; on every line in the named file. If it finds a ^M character at the end of a line, it is replaced with nothing. In other words, it will be removed. The &quot;$&quot; character following ^M indicates that the match will only mach ^M chars at the end of the line.

Following sed, we redirect output using &quot;>&quot; to a file in the /tmp directory.

Everything else is just moving the new file into place while keeping a copy of the original.

I leave it as an exercise for the reader to check if the named file exists and deal with this appropriately. :) [sig]<p> Andy Bold<br><a href=mailto: > </a><br><a href= > </a><br>"I've probably made most of the mistakes already, so hopefully you won't have to..." Me, most days.[/sig]
 
Many thanks Andy, just what I needed. A simple one liner, ain't it great when you know what you're doing ! Again thanks for taking the time to reply and for all the detail as well. [sig][/sig]
 
Simpler: dos2ux
where: /usr/bin
usage: dos2ux &quot;filename&quot; > &quot;new_filename&quot;

see man pages [sig][/sig]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top