Reputation: 66480
I have command line this:
xclip -o -sel clip | sed -e 's/^ *"\(.*\)"+\?/\1/g' | tr -d '\n' |
sed -e 's/.\{,55\}/"&"+\n/g' |
sed -e "2,$ s/^/$(seq 22 | xargs -I{} echo -n ' ')/" |
sed -e '$ s/+$//' | xclip -sel clip
which format string in source code (I use it to format long string in javascript file - 55 and 22 are harcoded width and indent)
var foo = "Lorem ipsum dolor sit amet, consectetur adipiscing elit"+
". Nulla sed dolor nisl, in suscipit justo. Donec a enim"+
" et est porttitor semper at vitae augue. Proin at nulla"+
" at dui mattis mattis. Nam a volutpat ante. Aliquam con"+
"sequat dui eu sem convallis ullamcorper."
but when I copy past code inside parentheses var foo = foo.bar()
I got this
var foo = foo.bar("Lorem ipsum dolor sit amet, consectetur adipiscing elit"+
". Nulla sed dolor nisl, in suscipit justo. Donec a enim"+
" et est porttitor semper at vitae augue. Proin at nulla"+
" at dui mattis mattis. Nam a volutpat ante. Aliquam con"+
"sequat dui eu sem convallis ullamcorper."
)
New line after last quote, not the big deal but anybody know how can I remove that last new line?
Upvotes: 0
Views: 644
Reputation: 241671
Here's one way of doing it, using awk
. Setting RS
(record separator) to the empty string tells awk
to treat blank lines (i.e. two consecutive \n
) as record separators. Setting FS
to \n
causes awk
to take \n
as field separators instead of white-space. (Setting RS
to the empty string also causes \n
to be used as a field separator, but we want to avoid having other whitespace recognized.) Finally, we set OFS
(output field separator) to be the string we want between lines (closing quote, plus, linefeed, 22 spaces, opening quote) and setting ORS
(output record separator) to an empty string causes awk
to not write any linefeed at the end.
I use fold
to split the lines into 55-byte chunks instead of sed, partly because it seems tidier, and partly because, unlike sed
, it doesn't add a new line at the end of the input if there wasn't one to start with.
The seemingly redundant $1=$1
causes awk
to recreate $0
, which has the effect of using OFS
as the output field separator between the fields. Otherwise, it is only used to separate separate print arguments.
The first and last line are unchanged from the OP.
xclip -o -sel clip | sed -e 's/^ *"\(.*\)"+\?/\1/g' | tr -d '\n' |
fold -b -w55 |
awk -vFS=$'\n' -vOFS="$(printf '"+\n%22s"' '')" \
-vRS='' -vORS='' \
'{$1=$1; print "\"" $0 "\""}' |
xclip -sel clip
Upvotes: 3