Обрезать строки до определенной длины [дубликат]

Совершенно честно, я не знаю, это ли именно то, что вы хотите. Все это время компиляции Perl/время выполнения меня немного сбивает с толку.

Вы можете попробовать autoexpect (включен в пакет expect). Первоначально вы должны запустить свое Perl-приложение через autoexpect, отвечая на входные данные. Но после этого вам нужно только запустить сценарий вывода, сгенерированный autoexpect, который заполняет все входные данные.

cat expect-test.pl

#!/bin/perl

use warnings;
use strict;

print "Enter your input: ";
my $input = <STDIN>;
chomp $input;
print "You typed: $input\n";

autoexpect -f expect-test.exp ./expect-test.pl
autoexpect started, file is expect-test.exp
Enter your input: bob 
You typed: bob
autoexpect done, file is expect-test.exp

./expect-test.exp
spawn ./expect-test.pl
Enter your input: bob 
You typed: bob

Или, проще говоря, вы также можете попробовать перенаправить входной файл в свой perl-скрипт:

cat input.text 
bart

./expect-test.pl < input.text 
Enter your input: You typed: bart
0
30.05.2018, 20:33
5 ответов

Consed:

sed 's/^\(.\{80\}\).*$/\1/' file

Concut:

cut -c -80 file 
0
28.01.2020, 02:13

Puede usar el comando cut:

cut -c -80 file

Congrep:

grep -Eo '.{80}' file
13
28.01.2020, 02:13

Para cortar (truncar )cada línea del archivo (y tener la salida en la consola actual )use:

cut -c -80 infile               # cut only counts bytes (fail with utf8)
grep -o '^.\{1,80\}' infile
sed 's/\(^.\{1,80\}\).*/\1/' infile

Si lo que desea es insertar una nueva línea en el carácter 80 y dividir cada línea de más de 80 caracteres en más líneas, use:

fold -w 80 infile            # fold, like cut, counts bytes.

Si desea dividir solo en espacios (palabras completas ), use:

fold -sw 80 infile

Para todas las soluciones anteriores, redirija a algún otro archivo como>outfile(no use el mismo nombre, eso no funcionará )al final de cualquier comando para almacenar el resultado en outfile. Ejemplo:

fold -sw 80 infile > outfile
4
28.01.2020, 02:13

Usando AWK:

awk '{print substr($0,1,80)}' file.txt

Usando cortar:

 cut -c -80 file.txt

Usando columna:

colrm 81 file.txt

Usando sed:

sed 's/^\(.\{80\}\).*$/\1/' file.txt

Usando grep:

grep -Eo '.{80}' file.txt
6
28.01.2020, 02:13

Использование Раку (урожденная Perl6)

~$ raku -ne 'put ~$0 if m/ ^^(. ** 80) /;'

ВЫХОД:

the of and to in a is that for it as was with be by on not he i this are or his
the of and to in a is that for it as was with be by on not he i this are or his
the of and to in a is that for it as was with be by on not he i this are or his
the of and to in a is that for it as was with be by on not he i this are or his
[TRUNCATED]

Приведенный выше код возвращает первые 80 символов строки (утверждение ^^нулевой -ширины означает «начало -строки -» ). Если строка слишком короткая, ничего не возвращается. Чтобы вернуть ДО 80 символов, используйте форму ** 1..80.

Нумерация снимков начинается с $0. Получите показания количества возвращаемых символов, добавив .charsк переменной захвата ~$0:

.
~$ raku -ne 'put ~$0.chars if m/ ^^(. ** 80) /;' ~/top50.txt
80
80
80
80
[TRUNCATED]

ХТН.

https://raku.org

0
25.09.2020, 02:19

Теги

Похожие вопросы