Когда вы запускаете скрипт в терминале, выполняется дочерний процесс. В этой дочерней программе, т. Е. Ваш скрипт изменится на любой указанный каталог. Но в родительском процессе, т.е. где вы запускаете скрипт, все еще находится в старом пути. ИЛИ просто мы можем сказать:
The scope of cd command is only for child process not parent
Я бы пошел с awk и что-то вроде этого:
awk -F " " '{print length($0), NF-1, $0}' file.txt
Если у вас есть несколько пробелов, используйте этот:
awk '{NS=gsub(" "," ",$0); print length($0), NS, $0}' file.txt
gsub заменяет каждое пространство с пробелом и возвращает счетчик этого процесса, который представляет собой количество пробелов. Допустим, у нас есть файл с этим контентом:
here is something
here is something el s
here is something else
and agai n
and a a aa
outpout из вышеприведенной команды:
17 2 here is something
22 4 here is something el s
22 3 here is something else
10 2 and agai n
10 3 and a a aa
Первый столбец - это число символы, второй - количество пробелов.
Затем мы передаем его на sort, а sort выполнит задание, и в конце концов я могу использовать разрез, чтобы получить исходное содержимое файла:
awk -F " " '{print length($0), NF-1, $0}' file.txt | sort -k1n,2 | cut -f3- -d' '
Для второго решения:
awk '{NS=gsub(" "," ",$0); print length($0), NS, $0}' file.txt | \
sort -k1n,2 | cut -f3- -d' '
И конечный результат:
and agai n
and a a aa
here is something
here is something else
here is something el s
Вы можете изменить -F " " своим конкретным персонажем «R»:
awk -F "R" ...
или
gsub("R","R",$0)
для второго.
Я бы пошел с awk и что-то вроде этого:
awk -F " " '{print length($0), NF-1, $0}' file.txt
Если у вас есть несколько пробелов, используйте этот:
awk '{NS=gsub(" "," ",$0); print length($0), NS, $0}' file.txt
gsub заменяет каждое пространство с пробелом и возвращает счетчик этого процесса, который представляет собой количество пробелов. Допустим, у нас есть файл с этим контентом:
here is something
here is something el s
here is something else
and agai n
and a a aa
outpout из вышеприведенной команды:
17 2 here is something
22 4 here is something el s
22 3 here is something else
10 2 and agai n
10 3 and a a aa
Первый столбец - это число символы, второй - количество пробелов.
Затем мы передаем его на sort, а sort выполнит задание, и в конце концов я могу использовать разрез, чтобы получить исходное содержимое файла:
awk -F " " '{print length($0), NF-1, $0}' file.txt | sort -k1n,2 | cut -f3- -d' '
Для второго решения:
awk '{NS=gsub(" "," ",$0); print length($0), NS, $0}' file.txt | \
sort -k1n,2 | cut -f3- -d' '
И конечный результат:
and agai n
and a a aa
here is something
here is something else
here is something el s
Вы можете изменить -F " " своим конкретным персонажем «R»:
awk -F "R" ...
или
gsub("R","R",$0)
для второго.
Я бы пошел с awk и что-то вроде этого:
awk -F " " '{print length($0), NF-1, $0}' file.txt
Если у вас есть несколько пробелов, используйте этот:
awk '{NS=gsub(" "," ",$0); print length($0), NS, $0}' file.txt
gsub заменяет каждое пространство с пробелом и возвращает счетчик этого процесса, который представляет собой количество пробелов. Допустим, у нас есть файл с этим контентом:
here is something
here is something el s
here is something else
and agai n
and a a aa
outpout из вышеприведенной команды:
17 2 here is something
22 4 here is something el s
22 3 here is something else
10 2 and agai n
10 3 and a a aa
Первый столбец - это число символы, второй - количество пробелов.
Затем мы передаем его на sort, а sort выполнит задание, и в конце концов я могу использовать разрез, чтобы получить исходное содержимое файла:
awk -F " " '{print length($0), NF-1, $0}' file.txt | sort -k1n,2 | cut -f3- -d' '
Для второго решения:
awk '{NS=gsub(" "," ",$0); print length($0), NS, $0}' file.txt | \
sort -k1n,2 | cut -f3- -d' '
И конечный результат:
and agai n
and a a aa
here is something
here is something else
here is something el s
Вы можете изменить -F " " своим конкретным персонажем «R»:
awk -F "R" ...
или
gsub("R","R",$0)
для второго.
На основе расширенной сортировки из обучения O'Reilly perl вы можете сделать что-то вроде
perl -lne '
push @arr, $_ }{
for $x (sort { length($a) <=> length($b) or $a =~ tr/ // <=> $b =~ tr/ // } @arr) {
print $x
}
' file
Заимствование Расширенная сортировка ,
$ perl -lne '
> push @arr, $_ }{
> for $x (sort { length($a) <=> length($b) or $a =~ tr/ // <=> $b =~ tr/ // } @arr) {
> print $x
> }
> ' loremipsum.txt
Omnis et vitae et blanditiis in et.
Inventore eligendi distinctio perferendis ab.
Nostrum laboriosam et amet illum consectetur.
Molestiae ipsam quis dolores vero a delectus.
Voluptas quos doloribus totam porro inventore.
Aut cupiditate ullam possimus voluptate et delectus tenetur sint.
Если у вас есть GNU awk 4.0 или новее, вы можете сделать аналогичную вещь, хотя функция пользовательской сортировки выполняет немного больше работы, например
$ cat 2sort.awk
#!/usr/bin/gawk -f
function mycmp(ia, a, ib, b) {
n = length(a) - length(b);
return n == 0 ? gsub(/ /,"",a) - gsub(/ /,"",b) : n
}
{arr[NR] = $0}
END {
PROCINFO["sorted_in"] = "mycmp";
for(i in arr) print arr[i];
}
, давая [!d7 ]
$ ./2sort.awk loremipsum.txt
Omnis et vitae et blanditiis in et.
Inventore eligendi distinctio perferendis ab.
Nostrum laboriosam et amet illum consectetur.
Molestiae ipsam quis dolores vero a delectus.
Voluptas quos doloribus totam porro inventore.
Aut cupiditate ullam possimus voluptate et delectus tenetur sint.
Вот небольшой скрипт Python, который выполняет эту работу. Обратите внимание, что он удаляет все конечные символы пробела из каждой строки перед сортировкой и на выходе.
#!/usr/bin/env python3
import sys
if len(sys.argv) != 2:
print("Error, you must specfy the input file name as only argument!")
exit(1)
lines=[line.rstrip() for line in open(sys.argv[1])]
print(*sorted(sorted(lines, key=lambda b:b.count(" ")), key=lambda a:len(a)),
sep="\n")
Если вы хотите сократить его, оставьте строки 3-5 out, которые только подтверждают, что ровно одна команда (если сценарий сохранен как sort.py и сделан исполняемый файл с помощью chmod +x sort.py) [!] ! d2]
$ cat loremipsum.txt
Nostrum laboriosam et amet illum consectetur.
Voluptas quos doloribus totam porro inventore.
Molestiae ipsam quis dolores vero a delectus.
Aut cupiditate ullam possimus voluptate et delectus tenetur sint.
Omnis et vitae et blanditiis in et.
Inventore eligendi distinctio perferendis ab.
$ ./sort.py loremipsum.txt
Omnis et vitae et blanditiis in et.
Inventore eligendi distinctio perferendis ab.
Nostrum laboriosam et amet illum consectetur.
Molestiae ipsam quis dolores vero a delectus.
Voluptas quos doloribus totam porro inventore.
Aut cupiditate ullam possimus voluptate et delectus tenetur sint.
Вот небольшой скрипт Python, который выполняет эту работу. Обратите внимание, что он удаляет все конечные символы пробела из каждой строки перед сортировкой и на выходе.
#!/usr/bin/env python3
import sys
if len(sys.argv) != 2:
print("Error, you must specfy the input file name as only argument!")
exit(1)
lines=[line.rstrip() for line in open(sys.argv[1])]
print(*sorted(sorted(lines, key=lambda b:b.count(" ")), key=lambda a:len(a)),
sep="\n")
Если вы хотите сократить его, оставьте строки 3-5 out, которые только подтверждают, что ровно одна команда (если сценарий сохранен как sort.py и сделан исполняемый файл с помощью chmod +x sort.py) [!] ! d2] $ cat loremipsum.txt
Nostrum laboriosam et amet illum consectetur.
Voluptas quos doloribus totam porro inventore.
Molestiae ipsam quis dolores vero a delectus.
Aut cupiditate ullam possimus voluptate et delectus tenetur sint.
Omnis et vitae et blanditiis in et.
Inventore eligendi distinctio perferendis ab.
$ ./sort.py loremipsum.txt
Omnis et vitae et blanditiis in et.
Inventore eligendi distinctio perferendis ab.
Nostrum laboriosam et amet illum consectetur.
Molestiae ipsam quis dolores vero a delectus.
Voluptas quos doloribus totam porro inventore.
Aut cupiditate ullam possimus voluptate et delectus tenetur sint.
На основе расширенной сортировки из обучения O'Reilly perl вы можете сделать что-то вроде
perl -lne '
push @arr, $_ }{
for $x (sort { length($a) <=> length($b) or $a =~ tr/ // <=> $b =~ tr/ // } @arr) {
print $x
}
' file
Заимствование Расширенная сортировка ,
$ perl -lne '
> push @arr, $_ }{
> for $x (sort { length($a) <=> length($b) or $a =~ tr/ // <=> $b =~ tr/ // } @arr) {
> print $x
> }
> ' loremipsum.txt
Omnis et vitae et blanditiis in et.
Inventore eligendi distinctio perferendis ab.
Nostrum laboriosam et amet illum consectetur.
Molestiae ipsam quis dolores vero a delectus.
Voluptas quos doloribus totam porro inventore.
Aut cupiditate ullam possimus voluptate et delectus tenetur sint.
Если у вас есть GNU awk 4.0 или новее, вы можете сделать аналогичную вещь, хотя функция пользовательской сортировки выполняет немного больше работы, например
$ cat 2sort.awk
#!/usr/bin/gawk -f
function mycmp(ia, a, ib, b) {
n = length(a) - length(b);
return n == 0 ? gsub(/ /,"",a) - gsub(/ /,"",b) : n
}
{arr[NR] = $0}
END {
PROCINFO["sorted_in"] = "mycmp";
for(i in arr) print arr[i];
}
, давая
$ ./2sort.awk loremipsum.txt
Omnis et vitae et blanditiis in et.
Inventore eligendi distinctio perferendis ab.
Nostrum laboriosam et amet illum consectetur.
Molestiae ipsam quis dolores vero a delectus.
Voluptas quos doloribus totam porro inventore.
Aut cupiditate ullam possimus voluptate et delectus tenetur sint.
Вот небольшой скрипт Python, который выполняет эту работу. Обратите внимание, что он удаляет все конечные символы пробела из каждой строки перед сортировкой и на выходе.
#!/usr/bin/env python3
import sys
if len(sys.argv) != 2:
print("Error, you must specfy the input file name as only argument!")
exit(1)
lines=[line.rstrip() for line in open(sys.argv[1])]
print(*sorted(sorted(lines, key=lambda b:b.count(" ")), key=lambda a:len(a)),
sep="\n")
Если вы хотите сократить его, оставьте строки 3-5 out, которые только подтверждают, что ровно одна команда (если сценарий сохранен как sort.py и сделан исполняемый файл с помощью chmod +x sort.py) [!] ! d2] $ cat loremipsum.txt
Nostrum laboriosam et amet illum consectetur.
Voluptas quos doloribus totam porro inventore.
Molestiae ipsam quis dolores vero a delectus.
Aut cupiditate ullam possimus voluptate et delectus tenetur sint.
Omnis et vitae et blanditiis in et.
Inventore eligendi distinctio perferendis ab.
$ ./sort.py loremipsum.txt
Omnis et vitae et blanditiis in et.
Inventore eligendi distinctio perferendis ab.
Nostrum laboriosam et amet illum consectetur.
Molestiae ipsam quis dolores vero a delectus.
Voluptas quos doloribus totam porro inventore.
Aut cupiditate ullam possimus voluptate et delectus tenetur sint.
На основе расширенной сортировки из обучения O'Reilly perl вы можете сделать что-то вроде
perl -lne '
push @arr, $_ }{
for $x (sort { length($a) <=> length($b) or $a =~ tr/ // <=> $b =~ tr/ // } @arr) {
print $x
}
' file
Заимствование Расширенная сортировка ,
$ perl -lne '
> push @arr, $_ }{
> for $x (sort { length($a) <=> length($b) or $a =~ tr/ // <=> $b =~ tr/ // } @arr) {
> print $x
> }
> ' loremipsum.txt
Omnis et vitae et blanditiis in et.
Inventore eligendi distinctio perferendis ab.
Nostrum laboriosam et amet illum consectetur.
Molestiae ipsam quis dolores vero a delectus.
Voluptas quos doloribus totam porro inventore.
Aut cupiditate ullam possimus voluptate et delectus tenetur sint.
Если у вас есть GNU awk 4.0 или новее, вы можете сделать аналогичную вещь, хотя функция пользовательской сортировки выполняет немного больше работы, например
$ cat 2sort.awk
#!/usr/bin/gawk -f
function mycmp(ia, a, ib, b) {
n = length(a) - length(b);
return n == 0 ? gsub(/ /,"",a) - gsub(/ /,"",b) : n
}
{arr[NR] = $0}
END {
PROCINFO["sorted_in"] = "mycmp";
for(i in arr) print arr[i];
}
, давая
$ ./2sort.awk loremipsum.txt
Omnis et vitae et blanditiis in et.
Inventore eligendi distinctio perferendis ab.
Nostrum laboriosam et amet illum consectetur.
Molestiae ipsam quis dolores vero a delectus.
Voluptas quos doloribus totam porro inventore.
Aut cupiditate ullam possimus voluptate et delectus tenetur sint.