Shell 能为我提供一个简单的搜索和替换脚本吗?
是否可以生成一个(在Mac OS X上运行的Perl或任何东西)脚本来转换Shell 能为我提供一个简单的搜索和替换脚本吗?,shell,replace,Shell,Replace,是否可以生成一个(在Mac OS X上运行的Perl或任何东西)脚本来转换 \section{long text} \sectionmark{short text} 到 或替代 \section{long text}[short text] 我无法确保长文本中没有换行符,或者\section和\sectionmark之间是否有换行符 这个问题与TeX.SX讨论的一个问题有关 awk '/\\section{long text}/ { oldline=$0
\section{long text}
\sectionmark{short text}
到
或替代
\section{long text}[short text]
我无法确保长文本中没有换行符
,或者\section
和\sectionmark
之间是否有换行符
这个问题与TeX.SX讨论的一个问题有关
awk '/\\section{long text}/ { oldline=$0
getline
gsub("{","[",oldline)
gsub("}","]",oldline)
print gensub("(.*)\\[(.*)\\]","\\1[\\2]{\\2","g",oldline) $0 "}"
getline
}
1' INPUTFILE
如果长文本中没有换行符
,并且\section
和\sectionmark
之间没有空行,将为您执行此操作。如果您有任何这些,您仍然可以修改它
所以要回答你的问题:是的,这是可能的
更新
下面是一个工作解决方案,使用awk
:
awk '/\\section{/ { oldline=$0
if ( oldline ~ /}/ ) {
lt=gensub(".*{([^}]+)}.*","\\1","g",oldline)
} else {
lt=gensub(".*{(.*)","\\1","g",oldline)
getline tmp
while ( tmp !~ "}" ) {
lt=lt "\n" tmp
getline tmp
}
lt=lt "\n" gensub("}.*","","g",tmp)
}
getline
while ( $0 !~ /\\sectionmark/ ) {
getline
}
printf("\\section[%s]{%s%s}\n",lt,lt,$0)
getline
}
! /\\section{/ { print }' INPUT_FILE
注意:如果在长文本}
和\sectionmark
之间出现任何内容,则它不处理,例如:
\section{long text}**THIS TEXT WILL BE SKIPPED!!**
\sectionmark{short text}
你可以从中看到它
如果您想删除
长文本中的新行,只需将脚本中的每个“\n”
替换为”
这可能适合您:
echo -e "\section{long text\nwith\nsome\nlinefeeds}\n\sectionmark{short text\nwith\nsome\nlinefeeds}" |
sed ':a;$!{N;ba};s/\(\\section{[^}]*}\)[\s\n]*\\sectionmark{\([^}]*\)}/\1[\2]/g'
\section{long text
with
some
linefeeds}[short text
with
some
linefeeds]
非常感谢你。如果长文本
中有换行符,请告诉我如何修改,因为有一些…这取决于具体情况。我的paypall地址是我在gmail.com的名字。。。好吧,这是一个蹩脚的笑话,但你应该付出一些努力。。。不管怎样,我有时会更新我的答案…再次感谢你,这为我节省了很多手工艺品和时间。“付出一些努力”通常情况下,我会这样做,不会在没有做一些自我调查和期望有人提供完整代码的情况下提问,但这次我不知道从哪里开始搜索,因为我从来没有编写过脚本,而且截止日期越来越近O:-)你有什么可以推荐的问题/任务/脚本资源吗像这样?对于使用bash
的常规脚本编写,我建议:对于常规文本处理:(sed
也是一个很好的工具,但是awk可以完成大部分工作)。
echo -e "\section{long text\nwith\nsome\nlinefeeds}\n\sectionmark{short text\nwith\nsome\nlinefeeds}" |
sed ':a;$!{N;ba};s/\(\\section{[^}]*}\)[\s\n]*\\sectionmark{\([^}]*\)}/\1[\2]/g'
\section{long text
with
some
linefeeds}[short text
with
some
linefeeds]