I have a data file, and I want to remove the first and last char. Is there a simple way to do this? I searched online, but I didn't find a simple way. Thanks!
Try:
sed -i '1s/.\(.*\)/\1/; $s/\(.*\)./\1/' path/to/file.txt
-i
: modify file in place
1s
: apply substitute command to line number 1 only
$s
: apply substitute command to last line only
\\( ... \\)
: a capture group to make use of later by referencing it with \\1
Basically these are two sed substitute commands glued with ;
EDIT: Just realized you said simple... Not sure if this falls under simple.
Could you please try following, if you are ok with awk
.
awk '
prev{
if(++count==1){
print substr(prev,2)
}
else{
print prev
}
prev=""
}
{
prev=$0
}
END{
if(prev){
print substr(prev,1,length(prev)-1)
}
}' Input_file
Using awk*. Testing with Lorem\\nipsum
(no trailing newline, as otherwise that would be removed**):
$ echo -en Lorem\\nipsum | awk -v RS="^$" '{gsub(/^.|.$/,"")}1'
orem
ipsu
Solution reads the whole input into memory before processing so that could be considered a downside.
* Succesfully tested with gawk, awk-20121220 and Busybox awk, failed with mawk.
** "Last character":
$ echo -e Lorem\\nipsum # outputs:
Lorem\n
ipsum\n # \n is last char but print (well, 1) adds another
To avoid that, use printf
instead:
$ echo -e Lorem\\nipsum | awk -v RS="^$" '{gsub(/^.|.$/,"");printf "%s",$0}'
orem
ipsum$
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.