LINUX.ORG.RU
ФорумAdmin

Использование sed c локальной переменной или совокупности команд вместо имени входного файла

 , , ,


0

1

При вызове sed c локальной переменной или совокупности команд вместо имени входного файла как правильно вызвать sed в этом случае конструкцию echo $var | sed просьба не предлагать вот листинг

# сначала с локальной переменной
b="c d"
echo $b
c d
sed 's/ /,/' $b
sed: can't read c: No such file or directory
sed: can't read d: No such file or directory
sed 's/ /,/' $(b)
b: command not found
^C
sed 's/ /,/' ($(b))
bash: syntax error near unexpected token `('
sed 's/ /,/' ($b)
bash: syntax error near unexpected token `('
sed 's/ /,/'$b
sed: -e expression #1, char 7: unknown option to `s'
sed 's/ /,/' $b
sed: can't read c: No such file or directory
sed: can't read d: No such file or directory
sed 's/ /,/' (<$b)
bash: syntax error near unexpected token `('
sed 's/ /,/' echo $b
sed: can't read echo: No such file or directory
sed: can't read c: No such file or directory
sed: can't read d: No such file or directory
sed 's/ /,/' $(echo $b)
sed: can't read c: No such file or directory
sed: can't read d: No such file or directory
sed 's/ /,/' $(echo $(b))
b: command not found
^C
sed 's/ /,/' $(echo $b)
sed: can't read c: No such file or directory
sed: can't read d: No such file or directory
sed 's/ /,/' $(echo ($b))
bash: command substitution: line 30: syntax error near unexpected token `$b'
bash: command substitution: line 30: `echo ($b))'
sed 's/ /,/' $(<($b))
bash: /dev/fd/63: Permission denied
c: command not found
^C
sed 's/ /,/' $(<$b)
bash: $b: ambiguous redirect
^C      
sed 's/ /,/' $(echo $b)
sed: can't read c: No such file or directory
sed: can't read d: No such file or directory
sed 's/ /,/' $(<echo $b)
bash: echo: No such file or directory
^C
sed 's/ /,/' <echo $b
bash: echo: No such file or directory
sed 's/ /,/' <<echo $b
> ^C
sed 's/ /,/' <echo $(b)
b: command not found
bash: echo: No such file or directory
sed 's/ /,/' <<echo $(b)
> ^C
sed 's/ /,/' $(b)
b: command not found
^C
sed 's/ /,/' '$b'
sed: can't read $b: No such file or directory
sed 's/ /,/' $(<b)
bash: b: No such file or directory
^C
sed 's/ /,/' $(<$b)
bash: $b: ambiguous redirect
^[[A^C
# кстати команда cat также не хочет работать с локальной переменной
cat $b
cat: c: No such file or directory
cat: d: No such file or directory
cat $(b)
b: command not found
^C
cat ($(b))
bash: syntax error near unexpected token `$(b)'
cat b
cat: b: No such file or directory
cat "$b"
cat: 'c d': No such file or directory
cat -n "$b"
cat: 'c d': No such file or directory
substr
substr: command not found
#########################################################
# листинг ко второй части вопроса
basename -a $(grep -Eo 'ht+ps*:/+[[:graph:]]+' /tmp/mtp
# mtp - список файлов вида file1.deb file2.deb и т.д.
basename -a $(grep -Eo 'ht+ps*:/+[[:graph:]]+' /tmp/mtp)| sed 's/\\n/,/g'
libmad0_0.15.1b-8ubuntu1_i386.deb
libid3tag0_0.15.1b-11_i386.deb
gmtp_1.3.9-2_i386.deb
golang-1.6-src_1.6.1-0ubuntu1_i386.deb
golang-1.6-go_1.6.1-0ubuntu1_i386.deb
golang-src_1.6-1ubuntu4_i386.deb
golang-go_1.6-1ubuntu4_i386.deb
jmtpfs_0.5-2_i386.deb
libattica0.4_0.4.2-2_i386.deb
libboost-thread1.58.0_1.58.0+dfsg-5ubuntu3_i386.deb
libprocess-cpp3_3.0.1-0ubuntu2_i386.deb
libdbus-cpp5_5.0.0+15.10.20151022.1-0ubuntu1_i386.deb
libgflags2v5_2.1.2-3_i386.deb
libgoogle-glog0v5_0.3.4-0.1_i386.deb
libdlrestrictions1_0.15.20~ubuntu4_i386.deb
libkdecore5_4.14.16-0ubuntu3_i386.deb
libkdeui5_4.14.16-0ubuntu3_i386.deb
libsolid4_4.14.16-0ubuntu3_i386.deb
libstreams0v5_0.7.8-2ubuntu1_i386.deb
libstreamanalyzer0v5_0.7.8-2ubuntu1_i386.deb
libkio5_4.14.16-0ubuntu3_i386.deb
libusb-1.0-0-dev_1.0.20-1_i386.deb
libmtp-dev_1.1.10-2ubuntu1_i386.deb
libmtp-doc_1.1.10-2ubuntu1_all.deb
libandroid-properties1_0.1.0+git20151016+6d424c9-0ubuntu7_i386.deb
libmtpserver1_0.0.4+15.04.20150219-0ubuntu3~gcc5.1_i386.deb
libmtpserver-dev_0.0.4+15.04.20150219-0ubuntu3~gcc5.1_i386.deb
mtp-server_0.0.4+15.04.20150219-0ubuntu3~gcc5.1_i386.deb
mtp-tools_1.1.10-2ubuntu1_i386.deb
mtpfs_1.1-5_i386.deb
qlix_0.2.6-0ubuntu5_i386.deb
golang-github-hanwen-go-fuse-dev_0.0~git20150627.0.324ea17-1_all.deb
golang-github-hanwen-usb-dev_0.0~git20141217.0.69aee45-2_all.deb
go-mtpfs_0.0~git20150802.0.3ef47f9-2_i386.deb
kio-extras-data_15.12.3-0ubuntu1_all.deb
kio-mtp_0.75+git20140304-2_i386.deb
kio-mtp-dbg_0.75+git20140304-2_i386.deb
libmtp-dbg_1.1.10-2ubuntu1_i386.deb
python-pymtp_0.0.6-1.1_all.deb

basename -a $(grep -Eo 'ht+ps*:/+[[:graph:]]+' /tmp/mtp)|sed 's/\ /,/g'
libmad0_0.15.1b-8ubuntu1_i386.deb
libid3tag0_0.15.1b-11_i386.deb
gmtp_1.3.9-2_i386.deb
golang-1.6-src_1.6.1-0ubuntu1_i386.deb
golang-1.6-go_1.6.1-0ubuntu1_i386.deb
golang-src_1.6-1ubuntu4_i386.deb
golang-go_1.6-1ubuntu4_i386.deb
jmtpfs_0.5-2_i386.deb
libattica0.4_0.4.2-2_i386.deb
libboost-thread1.58.0_1.58.0+dfsg-5ubuntu3_i386.deb
libprocess-cpp3_3.0.1-0ubuntu2_i386.deb
libdbus-cpp5_5.0.0+15.10.20151022.1-0ubuntu1_i386.deb
libgflags2v5_2.1.2-3_i386.deb
libgoogle-glog0v5_0.3.4-0.1_i386.deb
libdlrestrictions1_0.15.20~ubuntu4_i386.deb
libkdecore5_4.14.16-0ubuntu3_i386.deb
libkdeui5_4.14.16-0ubuntu3_i386.deb
libsolid4_4.14.16-0ubuntu3_i386.deb
libstreams0v5_0.7.8-2ubuntu1_i386.deb
libstreamanalyzer0v5_0.7.8-2ubuntu1_i386.deb
libkio5_4.14.16-0ubuntu3_i386.deb
libusb-1.0-0-dev_1.0.20-1_i386.deb
libmtp-dev_1.1.10-2ubuntu1_i386.deb
libmtp-doc_1.1.10-2ubuntu1_all.deb
libandroid-properties1_0.1.0+git20151016+6d424c9-0ubuntu7_i386.deb
libmtpserver1_0.0.4+15.04.20150219-0ubuntu3~gcc5.1_i386.deb
libmtpserver-dev_0.0.4+15.04.20150219-0ubuntu3~gcc5.1_i386.deb
mtp-server_0.0.4+15.04.20150219-0ubuntu3~gcc5.1_i386.deb
mtp-tools_1.1.10-2ubuntu1_i386.deb
mtpfs_1.1-5_i386.deb
qlix_0.2.6-0ubuntu5_i386.deb
golang-github-hanwen-go-fuse-dev_0.0~git20150627.0.324ea17-1_all.deb
golang-github-hanwen-usb-dev_0.0~git20141217.0.69aee45-2_all.deb
go-mtpfs_0.0~git20150802.0.3ef47f9-2_i386.deb
kio-extras-data_15.12.3-0ubuntu1_all.deb
kio-mtp_0.75+git20140304-2_i386.deb
kio-mtp-dbg_0.75+git20140304-2_i386.deb
libmtp-dbg_1.1.10-2ubuntu1_i386.deb
python-pymtp_0.0.6-1.1_all.deb

sed 's/\ /,/g' $(basename -a $(grep -Eo 'ht+ps*:/+[[:graph:]]+' /tmp/mtp))sed: can't read libmad0_0.15.1b-8ubuntu1_i386.deb: No such file or directory
sed: can't read libid3tag0_0.15.1b-11_i386.deb: No such file or directory
sed: can't read gmtp_1.3.9-2_i386.deb: No such file or directory
sed: can't read golang-1.6-src_1.6.1-0ubuntu1_i386.deb: No such file or directory
sed: can't read golang-1.6-go_1.6.1-0ubuntu1_i386.deb: No such file or directory
sed: can't read golang-src_1.6-1ubuntu4_i386.deb: No such file or directory
sed: can't read golang-go_1.6-1ubuntu4_i386.deb: No such file or directory
sed: can't read jmtpfs_0.5-2_i386.deb: No such file or directory
sed: can't read libattica0.4_0.4.2-2_i386.deb: No such file or directory
sed: can't read libboost-thread1.58.0_1.58.0+dfsg-5ubuntu3_i386.deb: No such file or directory
sed: can't read libprocess-cpp3_3.0.1-0ubuntu2_i386.deb: No such file or directory
sed: can't read libdbus-cpp5_5.0.0+15.10.20151022.1-0ubuntu1_i386.deb: No such file or directory
sed: can't read libgflags2v5_2.1.2-3_i386.deb: No such file or directory
sed: can't read libgoogle-glog0v5_0.3.4-0.1_i386.deb: No such file or directory
sed: can't read libdlrestrictions1_0.15.20~ubuntu4_i386.deb: No such file or directory
sed: can't read libkdecore5_4.14.16-0ubuntu3_i386.deb: No such file or directory
sed: can't read libkdeui5_4.14.16-0ubuntu3_i386.deb: No such file or directory
sed: can't read libsolid4_4.14.16-0ubuntu3_i386.deb: No such file or directory
sed: can't read libstreams0v5_0.7.8-2ubuntu1_i386.deb: No such file or directory
sed: can't read libstreamanalyzer0v5_0.7.8-2ubuntu1_i386.deb: No such file or directory
sed: can't read libkio5_4.14.16-0ubuntu3_i386.deb: No such file or directory
sed: can't read libusb-1.0-0-dev_1.0.20-1_i386.deb: No such file or directory
sed: can't read libmtp-dev_1.1.10-2ubuntu1_i386.deb: No such file or directory
sed: can't read libmtp-doc_1.1.10-2ubuntu1_all.deb: No such file or directory
sed: can't read libandroid-properties1_0.1.0+git20151016+6d424c9-0ubuntu7_i386.deb: No such file or directory
sed: can't read libmtpserver1_0.0.4+15.04.20150219-0ubuntu3~gcc5.1_i386.deb: No such file or directory
sed: can't read libmtpserver-dev_0.0.4+15.04.20150219-0ubuntu3~gcc5.1_i386.deb: No such file or directory
sed: can't read mtp-server_0.0.4+15.04.20150219-0ubuntu3~gcc5.1_i386.deb: No such file or directory
sed: can't read mtp-tools_1.1.10-2ubuntu1_i386.deb: No such file or directory
sed: can't read mtpfs_1.1-5_i386.deb: No such file or directory
sed: can't read qlix_0.2.6-0ubuntu5_i386.deb: No such file or directory
sed: can't read golang-github-hanwen-go-fuse-dev_0.0~git20150627.0.324ea17-1_all.deb: No such file or directory
sed: can't read golang-github-hanwen-usb-dev_0.0~git20141217.0.69aee45-2_all.deb: No such file or directory
sed: can't read go-mtpfs_0.0~git20150802.0.3ef47f9-2_i386.deb: No such file or directory
sed: can't read kio-extras-data_15.12.3-0ubuntu1_all.deb: No such file or directory
sed: can't read kio-mtp_0.75+git20140304-2_i386.deb: No such file or directory
sed: can't read kio-mtp-dbg_0.75+git20140304-2_i386.deb: No such file or directory
sed: can't read libmtp-dbg_1.1.10-2ubuntu1_i386.deb: No such file or directory
sed: can't read python-pymtp_0.0.6-1.1_all.deb: No such file or directory

Перемещено hobbit из general

Что это за понос? В на собеседовании или зачёт сдаёте?

кстати команда cat также не хочет работать с локальной переменной

А что должна сделать команда ″cat″? Она ожидает в командной строке имена файлов, ″bash″ туда подставляет значение переменной, ″cat″ пытается их прочитать. Прочитать файлы, а не переменную.

sed ждёт данных с stdin, в командной строке он ждёт имена файлов.

Стандартный способо подать что-то на stdin это ″|″ (палка/pipe). Вместо echo может быть printf. Или ″<<<″ (три знака меньше).

https://stackoverflow.com/questions/4775548/how-to-pass-the-value-of-a-variab...

mky ★★★★★
()

яннп. Ожидаемый результат какой был?

И если echo $var | sed таки делает то, что вам надо было (что по листингу дальше никак не скажешь), то почему не предлагать?

CrX ★★★
()
Последнее исправление: CrX (всего исправлений: 1)
Ответ на: комментарий от mky

Или BSDшники bash и zsh не различают?

Ещё раз для тех, кто читает по диагонали:

не совместимый с POSIX.

Так что в данном случае не важно, bash или zsh.

mord0d ★★★★★
()
Ответ на: комментарий от mord0d

Совместимость с POSIX не фетиш в мире GNU. POSIX с этим согласен и потихоньку включает в себя некоторые GNU-расширения.

mky ★★★★★
()
Ответ на: комментарий от mky

Совместимость с POSIX не фетиш в мире GNU.

Разработать стандарт и покласть на него МПХ. Поэтому линуксизмы не переносимы за пределы линуксов. Троллейбус из буханки хлеба. (%

mord0d ★★★★★
()
Последнее исправление: mord0d (всего исправлений: 2)
Ответ на: комментарий от mord0d

GNU не разрабатывало POSIX, вот интервью Столлмана касательно POSIX. https://opensource.com/article/19/7/what-posix-richard-stallman-explains. Стандарт — хорошо, но удобство пользователей (users' convenience) важны.

И я не знаю ни одной ОС, которая на 100% соответствует POSIX. Не знаю, те операционки, которые были до POSIX, они после выхода первых версий POSIX как-то урезали/изменили функционал своих утилит в последующих версиях или оставили как есть, чтобы не терять совместимость?

Писать портируемый скрипт — это не только без bash'измов, — это, например, не забывать опцию ″-k″ у команды ″du″, в GNU она по-умолчанию, размер в 1кБ блоках, а по POSIX, по-умолчанию, размер в 512 байт блоках. Помнить все подобные ключи сложно, скрипт нужно тестировать, и тестировать в 100% POSIX среде, которой нет. Написать скрипт на POSIX-shell одно, а написать сложный скрипт, который корректно отработает под Linux, OpenBSD и AIX совсем другое.

Если уж запрещать bash-измы, то есть скрипты, написаные на bash, то запрещать и отстальные скриптовые ЯП, чем скрипт на bash хуже скрипта на perl?

mky ★★★★★
()
Ответ на: комментарий от mky

Если уж запрещать bash-измы

Я не предлагаю ничего запрещать. Мой посыл в том, чтобы помнить, что некоторые вещи не будут работать за пределами тестируемого окружения. Если ты пишешь скрипт, то учесть всех нюансов в одну каску ты не сможешь физически, но нужно иметь в виду возможность переносимости и оставлять пространство для расширения/модификации в тех местах, где оно может понадобиться при портировании.

mord0d ★★★★★
()
Для того чтобы оставить комментарий войдите или зарегистрируйтесь.