sed 또는 awk와 같은 일반적인 명령 줄 도구를 사용하면 백 슬래시와 같이 주어진 문자로 끝나는 모든 줄을 연결할 수 있습니까?
예를 들어 파일이 다음과 같습니다.
foo bar \
bash \
baz
dude \
happy
이 출력을 얻고 싶습니다 :
foo bar bash baz
dude happy
답변
더 짧고 간단한 sed 솔루션 :
sed '
: again
/\\$/ {
N
s/\\\n//
t again
}
' textfile
또는 GNU를 사용하는 경우 하나의 라이너 sed
:
sed ':x; /\\$/ { N; s/\\\n//; tx }' textfile
답변
perl을 사용하는 것이 가장 쉬울 것입니다.
perl -p -e 's/\\\n//'
답변
다음은 awk 솔루션입니다. 줄이로 끝나는 경우 \
백 슬래시를 제거하고 줄 바꿈없이 줄을 인쇄하십시오. 그렇지 않으면 줄 바꿈으로 줄을 인쇄하십시오.
awk '{if (sub(/\\$/,"")) printf "%s", $0; else print $0}'
답변
이것은 대답이 아닙니다. 에 대한 부수적 인 문제 sed
입니다.
구체적으로, 나는 Gilles의 sed
명령 을 하나씩 분해하여 이해해야했습니다 … 나는 그것에 대해 약간의 노트를 작성하기 시작했고, 여기 누군가에게 유용 할 것이라고 생각했습니다 …
그래서 여기있다 … 질 ‘나오지도 스크립트 의 기록 형식 :
#!/bin/bash
#######################################
sed_dat="$HOME/ztest.dat"
while IFS= read -r line ;do echo "$line" ;done <<'END_DAT' >"$sed_dat"
foo bar \
bash \
baz
dude \
happy
yabba dabba
doo
END_DAT
#######################################
sedexec="$HOME/ztest.sed"
while IFS= read -r line ;do echo "$line" ;done <<'END-SED' >"$sedexec"; \
sed -nf "$sedexec" "$sed_dat"
s/\\$// # If a line has trailing '\', remove the '\'
#
t'Hold-append' # branch: Branch conditionally to the label 'Hold-append'
# The condition is that a replacement was made.
# The current pattern-space had a trailing '\' which
# was replaced, so branch to 'Hold-apend' and append
# the now-truncated line to the hold-space
#
# This branching occurs for each (successive) such line.
#
# PS. The 't' command may be so named because it means 'on true'
# (I'm not sure about this, but the shoe fits)
#
# Note: Appending to the hold-space introduces a leading '\n'
# delimiter for each appended line
#
# eg. compare the hex dump of the follow 4 example commands:
# 'x' swaps the hold and patten spaces
#
# echo -n "a" |sed -ne 'p' |xxd -p ## 61
# echo -n "a" |sed -ne 'H;x;p' |xxd -p ## 0a61
# echo -n "a" |sed -ne 'H;H;x;p' |xxd -p ## 0a610a61
# echo -n "a" |sed -ne 'H;H;H;x;p' |xxd -p ## 0a610a610a61
# No replacement was made above, so the current pattern-space
# (input line) has a "normal" ending.
x # Swap the pattern-space (the just-read "normal" line)
# with the hold-space. The hold-space holds the accumulation
# of appended "stripped-of-backslah" lines
G # The pattern-space now holds zero to many "stripped-of-backslah" lines
# each of which has a preceding '\n'
# The 'G' command Gets the Hold-space and appends it to
# the pattern-space. This append action introduces another
# '\n' delimiter to the pattern space.
s/\n//g # Remove all '\n' newlines from the pattern-space
p # Print the pattern-space
s/.*// # Now we need to remove all data from the pattern-space
# This is done as a means to remove data from the hold-space
# (there is no way to directly remove data from the hold-space)
x # Swap the no-data pattern space with the hold-space
# This leaves the hold-space re-initialized to empty...
# The current pattern-space will be overwritten by the next line-read
b # Everything is ready for the next line-read. It is time to make
# an unconditional branch the to end of process for this line
# ie. skip any remaining logic, read the next line and start the process again.
:'Hold-append' # The ':' (colon) indicates a label..
# A label is the target of the 2 branch commands, 'b' and 't'
# A label can be a single letter (it is often 'a')
# Note; 'b' can be used without a label as seen in the previous command
H # Append the pattern to the hold buffer
# The pattern is prefixed with a '\n' before it is appended
END-SED
#######
답변
또 다른 일반적인 명령 줄 도구는 ed
기본적으로 파일을 제자리에서 수정하므로 파일 권한을 수정하지 않은 상태로 둡니다 (자세한 내용 은 스크립트에서 ed 텍스트 편집기로 파일 편집ed
참조 ).
str='
foo bar \
bash 1 \
bash 2 \
bash 3 \
bash 4 \
baz
dude \
happy
xxx
vvv 1 \
vvv 2 \
CCC
'
# We are using (1,$)g/re/command-list and (.,.+1)j to join lines ending with a '\'
# ?? repeats the last regex search.
# replace ',p' with 'wq' to edit files in-place
# (using Bash and FreeBSD ed on Mac OS X)
cat <<-'EOF' | ed -s <(printf '%s' "$str")
H
,g/\\$/s///\
.,.+1j\
??s///\
.,.+1j
,p
EOF
답변
read
쉘없이 백 슬래시를 해석 한다는 사실을 사용하면 -r
:
$ while IFS= read line; do printf '%s\n' "$line"; done <file
foo bar bash baz
dude happy
이는 데이터의 다른 백 슬래시 도 해석합니다 .
답변
전체 파일을 메모리에로드하는 간단한 솔루션입니다.
sed -z 's/\\\n//g' file # GNU sed 4.2.2+.
또는 이해 (출력) 줄 (GNU 구문)을 작동하는 여전히 짧은 것 :
sed ':x;/\\$/{N;bx};s/\\\n//g' file
한 줄에 (POSIX 구문) :
sed -e :x -e '/\\$/{N;bx' -e '}' -e 's/\\\n//g' file
또는 awk를 사용하십시오 (파일이 너무 커서 메모리에 맞지 않는 경우).
awk '{a=sub(/\\$/,"");printf("%s%s",$0,a?"":RS)}' file