Reputation: 101
I want to remove the first two characters of a column in a text file. I am using the below but this is also truncating the headers.
sed -i 's/^..//' file1.txt
Below is my file:
FileName,Age
./Acct_Bal_Tgt.txt,7229
./IDQ_HB1.txt,5367
./IDQ_HB_LOGC.txt,5367
./IDQ_HB.txt,5367
./IGC_IDQ.txt,5448
./JobSchedule.txt,3851
I want the ./
to be removed from each line in the file name.
Upvotes: 1
Views: 547
Reputation: 754400
Transferring comments to an answer, as requested.
Modify your script to:
sed -e '2,$s/^..//' file1.txt
The 2,$
prefix limits the change to lines 2 to the end of the file, leaving line 1 unchanged.
An alternative is to remove .
and /
as the first two characters on a line:
sed -e 's%^[.]/%%' file1.txt
I tend to use -e
to specify that the script option follows; it isn't necessary unless you split the script over several arguments (so it isn't necessary here where there's just one argument for the script). You could use \.
instead of [.]
; I'm allergic to backslashes (as you would be if you ever spent time working out whether you needed 8 or 16 consecutive backslashes to get the right result in a troff
document).
Advice: Don't use the -i
option until you've got your script working correctly. It overwrites your file with the incorrect output just as happily as it will with the correct output. Consequently, if you're asking about how to write a sed
script on SO, it isn't safe to be using the -i
option. Also note that the -i
option is non-standard and behaves differently with different versions of sed
(when it is supported at all). Specifically, on macOS, the BSD sed
requires a suffix specified; if you don't want a backup, you have to use two arguments: -i ''
.
Upvotes: 1
Reputation: 12367
Use this Perl one-liner:
perl -pe 's{^[.]/}{}' file1.txt > output.txt
The Perl one-liner uses these command line flags:
-e
: Tells Perl to look for code in-line, instead of in a file.
-p
: Loop over the input one line at a time, assigning it to $_
by default. Add print $_
after each loop iteration.
s{^[.]/}{}
: Replace a literal dot ([.]
) followed by a slash ('/'), found at the beginning of the line (^
), with nothing (delete them). This does not modify the header since it does not match the regex.
If you prefer to modify the file in-place, you can use this:
perl -i.bak -pe 's{^[.]/}{}' file1.txt
This creates the backup file file1.txt.bak
.
SEE ALSO:
perldoc perlrun
: how to execute the Perl interpreter: command line switches
perldoc perlrequick
: Perl regular expressions quick start
Upvotes: 0