Nice programing

파일의 각 줄에서 선행 공백을 제거하는 방법

nicepro 2020. 11. 26. 19:49
반응형

파일의 각 줄에서 선행 공백을 제거하는 방법


다음과 같은 파일이 있습니다.

for (i = 0; i < 100; i++)
    for (i = 0; i < 100; i++)
  for (i = 0; i < 100; i++)
       for (i = 0; i < 100; i++)
     for (i = 0; i < 100; i++)
           for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)

다음과 같이 보이기를 원합니다 (들여 쓰기 제거).

for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)

어떻게 할 수 sed있습니까 ( 아마도 사용 ?)?


sed "s/^[ \t]*//" -i youfile

경고 : 원본 파일을 덮어 씁니다.


이 특정 문제의 경우 다음과 같이 작동합니다.

$ sed 's/^ *//g' < input.txt > output.txt

줄의 시작 부분에있는 모든 공백을 아무것도없는 것으로 바꾸라고합니다. 탭도 제거하려면 다음과 같이 변경하십시오.

$ sed 's/^[ \t]+//g' < input.txt > output.txt

/ 앞의 "s"는 "대체"를 의미합니다. /는 패턴의 구분 기호입니다. 처음 두 / 사이의 데이터는 일치시킬 패턴이고 두 번째와 세 번째 / 사이의 데이터는이를 대체 할 데이터입니다. 이 경우 아무것도 교체하지 않습니다. 마지막 슬래시 뒤의 "g"는 "전역 적으로"수행하는 것을 의미합니다. 즉, 찾은 첫 번째 일치 항목에서만이 아니라 전체 파일에 대해 수행합니다.

마지막으로, 대신 파일을 "제자리에서"편집하는 옵션을 < input.txt > output.txt사용할 수 있습니다 -i. 결과를 포함하기 위해 두 번째 파일을 만들 필요가 없습니다. 이 옵션을 사용하면 원본 파일이 손실됩니다.


AWK를 사용할 수 있습니다.

$ awk '{$1=$1}1' file
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)

sed

$ sed 's|^[[:blank:]]*||g' file
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)

쉘의 while/ read루프

while read -r line
do
    echo $line
done <"file"

이 Perl 코드는 원본 파일을 편집합니다.

perl -i -ne 's/^\s+//;print' file

The next one makes a backup copy before editing the original file:

perl -i.bak -ne 's/^\s+//;print' file

Notice that Perl borrows heavily from sed (and awk)


Here you go:

user@host:~$ sed 's/^[\t ]*//g' < file-in.txt

Or:

user@host:~$ sed 's/^[\t ]*//g' < file-in.txt > file-out.txt

sed -e 's/^[ \t]*//' name_of_file_from_which_you_want_to_remove_space >'name _file_where_you_want_to_store_output'

e.g:- sed -e 's/^[ \t]*//' file1.txt > output.txt

Note:

s/ : Substitute command ~ replacement for pattern (^[ \t]*) on each addressed line

^[ \t]* : Search pattern ( ^ – start of the line; [ \t]* match one or more blank spaces including tab)

// : Replace (delete) all matched pattern


FWIW, if you are editing this file, you can probably highlight all the lines and use your un-tab button.

  • In vim, use shift-v to highlight the lines, then press <<
  • If you're on a mac, then you can use Atom, Sublime, etc., then highlight with your mouse and then press shift-tab

Not sure if there is some requirement that this must be done from the command line. If so, then :thumbs-up: to the accepted answer! =)

참고URL : https://stackoverflow.com/questions/2310605/how-to-remove-leading-whitespace-from-each-line-in-a-file

반응형