Reputation: 2217
I'm rather noob on bash (or perl). Looking a way to modify some lines in a file, (basically removing the first 2 characters of each line, and add a "," at the end of each line)
###element
##.element
###test-element-00
becomes the following,
#element,
.element,
#test-element-00,
Thanks
Upvotes: 0
Views: 330
Reputation: 15572
Bash can handle this just fine: line="##element"; echo "${line#??},"
Upvotes: 0
Reputation: 1
Here's yet another to way to do it using the ed command:
str='
###element
##.element
###test-element-00
'
# for in-place file editing use "ed -s file" and replace ",p" with "w"
# cf. http://wiki.bash-hackers.org/howto/edit-ed
cat <<-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | ed -s <(echo "$str")
H
,g/.\{2\}/s/^..\(.*\)$/\1,/
,p
q
EOF
Upvotes: 0
Reputation: 385506
perl -ple's/..(.*)/$1,/' infile > outfile
perl -ple's/..//;s/$/,/' infile > outfile
Using in-place editing:
perl -i -ple's/..(.*)/$1,/' file
perl -i -ple's/..//;s/$/,/' file
Upvotes: 5
Reputation: 359855
OK, just for variety:
yes , | head -n $(wc -l < filename) | paste -d '' <(cut -c3- filename) -
or
yes , | head -n $(wc -l < filename) | paste -d '' <(grep -Po '..\K.*' filename) -
Requires a shell, such as Bash, that supports process substitution. For the grep
version, support for Perl Compatible Regular Expressions is required.
Upvotes: 0
Reputation: 455
There are several ways of doing this, one way of doing this in perl would be :
$line = '##element'
$line = substr ( $line, 2 ) . ',';
Upvotes: 0
Reputation: 25599
awk
$> awk '/^#/ { print substr($0,3)"," }' file
#element,
.element,
#test-element-00,
Ruby(1.9+)
$> ruby -ne 'print "#{$_.chomp[2..-1]},\n" if /^#/' file
#element,
.element,
#test-element-00,
Or just pure bash
$> while read -r line; do echo "${line:2},"; done < file
#element,
.element,
#test-element-00,
or sed if you prefer
$> sed 's/^..//;s/$/,/' file
#element,
.element,
#test-element-00,
Upvotes: 0
Reputation: 6309
Try something like this:
my @old_lines = qw(###element ##.element ###test-element-00);
my @new_lines;
for my $line (@old_lines) {
$line =~ s/^##//;
$line .= ',';
push @new_lines, $line;
}
print "@new_lines";
Upvotes: 0
Reputation: 444
On bash the command you are looking for is sed, try:
cat filename | sed 's/^..\(.*\)$/\1,/'
Upvotes: 2
Reputation: 434585
A bit of simple sed(1) is all you need for that:
sed 's/^..//' < your_file | sed 's/$/,/'
Or you can use Perl if you really want to:
perl -pe 's/^..(.*)/$1,/' < your_file
Or you can even do it with cut(1), xargs(1), and printf(1):
cut -c2- < your_file | xargs printf '%s,\n'
We could probably be here all night coming with clever combinations of shell tools to perform the desired transformation, I'd probably just go with the perl one and move on to more productive things.
The sed
approach can probably be done better but my sed is rusty.
Upvotes: 1